/********* src/directives/waterMark.ts  ***********/ 

// 全局保存 canvas 和 div ，避免重复创建（单例模式）
const globalCanvas = null
const globalWaterMark = null

// 获取 toDataURL 的结果
const getDataUrl = ({
  font = '16px normal',
  fillStyle = 'rgba(180, 180, 180, 0.3)',
  textAlign,
  textBaseline,
  text = '请勿外传',
}) => {
  const rotate = -20
  const canvas = globalCanvas || document.createElement('canvas')
  const ctx = canvas.getContext('2d') // 获取画布上下文

  ctx.rotate((rotate * Math.PI) / 180)
  ctx.font = font
  ctx.fillStyle = fillStyle
  ctx.textAlign = textAlign || 'left'
  ctx.textBaseline = textBaseline || 'middle'
  ctx.fillText(text, canvas.width / 3, canvas.height / 2)

  return canvas.toDataURL('image/png')
}

// 设置水印
const setWaterMark = (el, binding) => {
  const { parentElement } = el

  // 获取对应的 canvas 画布相关的 base64 url
  const url = getDataUrl(binding)

  // 创建 waterMark 父元素
  const waterMark = globalWaterMark || document.createElement('div')
  waterMark.className = `water-mark` // 方便自定义展示结果
  waterMark.setAttribute('style', `background-image: url(${url});`)

  // 将对应图片的父容器作为定位元素
  parentElement.setAttribute('style', 'position: relative;')

  // 将图片元素移动到 waterMark 中
  parentElement.appendChild(waterMark)
}

const directives = {
  mounted(el, binding) {
    el.onload = setWaterMark.bind(null, el, binding.value)
  },
}

export default {
  name: 'watermark',
  directives,
}
